package cn.xiangxu.webfulx_structure.controller;

import java.io.File;
import java.io.IOException;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ZeroCopyHttpOutputMessage;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;

import reactor.core.publisher.Mono;

/**
 * 文件名称： com.ledi.lxs.controller.FileController.java<br/>
 * 初始作者： 钟小平<br/>
 * 创建日期： 2018年9月14日<br/>
 * 功能说明： 文件上传下载<br/>
 * =================================================<br/>
 * 修改记录：<br/>
 * 修改作者 日期 修改内容<br/>
 * ================================================<br/>
 * Copyright (乐迪教育科技有限公司-幼儿事业部) 2017-2018.All rights reserved.<br/>
 */
@RestController
@RequestMapping("/file")
public class FileController {

	@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
	public Mono<String> requestBodyFlux(@RequestPart("file") FilePart filePart) throws IOException {

		System.out.println(filePart.filename());
		Path tempFile = Files.createTempFile("test", filePart.filename());

		// NOTE 方法一
		AsynchronousFileChannel channel =
				AsynchronousFileChannel.open(tempFile, StandardOpenOption.WRITE);
		DataBufferUtils.write(filePart.content(), channel, 0)
				.doOnComplete(() -> {
					System.out.println("finish");
				})
				.subscribe();

		// NOTE 方法二
		// filePart.transferTo(tempFile.toFile());

		System.out.println(tempFile.toString());
		return Mono.just(filePart.filename());
	}

	@GetMapping("/download")
	public Mono<Void> downloadByWriteWith(ServerHttpResponse response) throws IOException {

		ZeroCopyHttpOutputMessage zeroCopyResponse = (ZeroCopyHttpOutputMessage) response;
		response.getHeaders().set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=parallel.png");
		response.getHeaders().setContentType(MediaType.IMAGE_PNG);

		Resource resource = new ClassPathResource("parallel.png");
		File file = resource.getFile();
		return zeroCopyResponse.writeWith(file, 0, file.length());
	}

}
